import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class WarehouseRelocation extends StatefulWidget {
  const WarehouseRelocation({super.key});
  @override
  State<WarehouseRelocation> createState() => _WarehouseRelocationState();
}

class _WarehouseRelocationState extends State<WarehouseRelocation> {
  final _formKey = GlobalKey<FormState>(); // 表单Key
  final GlobalKey<_WarehouseRelocationState> formKey =
      GlobalKey<_WarehouseRelocationState>();
  final _outWarehouseController = TextEditingController();
  final _inWarseHouseController = TextEditingController();
  final _skuCodeController = TextEditingController();
  final _pickController = TextEditingController();
  final _remarkController = TextEditingController();

  final _outhouseFocusNode = FocusNode();
  final _inHouseFocusNode = FocusNode();
  final _skuCodeFocusNode = FocusNode();
  final _pickNumFocusNode = FocusNode();
  final _remarkFocusNode = FocusNode();
  List dataList = [];
  List<StorageBatchItem> storageBatchItemList = <StorageBatchItem>[];
  String rowId = '';
  StorageBatchItem? _selectRow;
  // 获取sku信息
  Future<void> _getInfoRequest(BuildContext context) async {
    try {
      if (_outWarehouseController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入移出库位'), duration: Duration(seconds: 3)),
        );
        return;
      }
      if (_skuCodeController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入SKU编码'), duration: Duration(seconds: 3)),
        );
        return;
      }
      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/imSkuStorageBatch/groupLocationCount',
        data: {
          'skuCode': _skuCodeController.text,
          'locationCode': _outWarehouseController.text,
          'pageNum': 1,
          'pageSize': 100,
        },
      );
      if (response.code == 200 && response.data != null) {
        if (response.data is Map<String, dynamic>) {
          final dataMap = response.data as Map<String, dynamic>;
          if (dataMap['rows'] is List<dynamic>) {
            setState(() {
              dataList = dataMap['rows'];
            });
          }
        }
        if (dataList.isNotEmpty) {
          _getBatchInfoRequest(
            context,
            dataList[0]['storageImSkuStorageSummaryId'],
          );
        }
      }
      print('response---$response');
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 获取批次信息
  Future<void> _getBatchInfoRequest(
    BuildContext context,
    storageImSkuStorageSummaryId,
  ) async {
    try {
      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/imSkuStorageSummary/batchListAllBySummaryId',
        data: {'storageImSkuStorageSummaryId': storageImSkuStorageSummaryId},
      );
      if (response.code == 200 && response.data != null) {
        if (response.data is List<dynamic>) {
          final dataMap = response.data as List<dynamic>;
          setState(() {
            storageBatchItemList = dataMap
                .map((item) => StorageBatchItem.fromJson(item))
                .toList();
          });
        }
      }
      print('response---$response');
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 提交信息
  void _submitInfoRequest(BuildContext context) async {
    try {
      if (dataList.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请先获取sku信息'), duration: Duration(seconds: 3)),
        );
        return;
      }
      if (_inWarseHouseController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入移入库位'), duration: Duration(seconds: 3)),
        );
        return;
      }
      if (_pickController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入移库数量'), duration: Duration(seconds: 3)),
        );
        return;
      }

      LoadingOverlay.show(context);
      final response = await HttpUtil.post(
        '/storage/imSkuStockTransfer/add',
        data: {
          'skuId': dataList[0]['skuId'],
          'warehouseId': dataList[0]['warehouseId'],
          'storageImSkuStorageSummaryId':
              dataList[0]['storageImSkuStorageSummaryId'],
          'locationId': _outWarehouseController.text,
          // 目标库位
          'targerLocationId': _inWarseHouseController.text,
          'remark': _remarkController.text,
          'batchList': _selectRow.toString() != 'null'
              ? [
                  {
                    'storageImSkuStorageBatchId':
                        _selectRow?.storageImSkuStorageBatchId,
                    'transferCount': _pickController.text,
                    'remark': _remarkController.text,
                  },
                ]
              : [],
        },
      );
      if (response.code == 200 && response.data != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('移库成功'), duration: Duration(seconds: 3)),
        );
        _resetForm();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('提交失败---${response.message}'),
            duration: Duration(seconds: 3),
          ),
        );
      }
      print('response---$response');
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  void _resetForm() {
    setState(() {
      _outWarehouseController.clear();
      _inWarseHouseController.clear();
      _skuCodeController.clear();
      _pickController.clear();
      _remarkController.clear();
      dataList = [];
      storageBatchItemList = [];
      rowId = '';
      _selectRow = null;
    });
    _outhouseFocusNode.requestFocus();
  }

  // 选择批次
  void _onRowSelected(item) {
    setState(() {
      rowId = item.storageImSkuStorageBatchId;
      _selectRow = item;
    });
    print('rowId---$rowId,$item');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(title: const Text("移库")),
      appBar: const TopHeader(title: '移库'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 收货单号
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('移出库位', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _outWarehouseController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _outWarehouseController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _outWarehouseController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _outWarehouseController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _outhouseFocusNode,
                        onFieldSubmitted: (value) {
                          _getInfoRequest(context);
                          _skuCodeFocusNode.requestFocus();
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('SKU编码', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _skuCodeController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _skuCodeController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _skuCodeController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _skuCodeController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _skuCodeFocusNode,
                        onFieldSubmitted: (value) {
                          _getInfoRequest(context);

                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('移库数量', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        controller: _pickController,

                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入数字';
                          }
                          if (int.tryParse(value) == null) {
                            return '请输入有效的数字';
                          }
                          return null;
                        },
                        focusNode: _pickNumFocusNode,
                        onFieldSubmitted: (value) {
                          _getInfoRequest(context);

                          print('回车执行');
                        },
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 8,
                          ),
                          // labelText: '数字输入',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: Colors.grey[300]!),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: Colors.grey[300]!),
                          ),
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _pickController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _pickController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('移入库位', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _inWarseHouseController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _inWarseHouseController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _inWarseHouseController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _inWarseHouseController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _inHouseFocusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          // getInfo(
                          //   incomingGoodsNo: _incomingGoodsController.text,
                          // );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('备注', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 10,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _remarkController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _remarkController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _remarkController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _remarkController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _remarkFocusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          // getInfo(
                          //   incomingGoodsNo: _incomingGoodsController.text,
                          // );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              // 添加列表展示区域
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: _buildList(),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        _resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        _submitInfoRequest(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('提交'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表展示
  Widget _buildList() {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      child: storageBatchItemList.isNotEmpty
          ? DataTable(
              columnSpacing: 20,
              showCheckboxColumn: false,
              columns: const [
                DataColumn(label: Text('采购单号/上架单号')),

                DataColumn(label: Text('操作')),
              ],
              rows: storageBatchItemList.isNotEmpty
                  ? storageBatchItemList.map((item) {
                      return DataRow(
                        // selected: rowId == item.storageImSkuStorageBatchId,
                        selected: rowId == item.storageImSkuStorageBatchId,

                        onSelectChanged: (selected) => _onRowSelected(item),
                        cells: [
                          DataCell(
                            SizedBox(
                              width: 250,
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        item.purchaseOrderNo,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        item.storagePutOnSaleNo,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),

                          DataCell(
                            SizedBox(
                              width: 50,
                              child: GestureDetector(
                                onTap: () {
                                  _onRowSelected(item);
                                },
                                child: Text(
                                  '选择',
                                  style: TextStyle(
                                    color: const Color.fromARGB(
                                      255,
                                      74,
                                      61,
                                      187,
                                    ),
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      );
                    }).toList()
                  : [],
            )
          : SizedBox(
              width: MediaQuery.of(context).size.width,
              height: 200,
              child: Center(
                child: Text(
                  '暂无数据',
                  style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                ),
              ),
            ),
    );
  }
}

// 构建标签文本
Widget _buildLabel(String text, {bool isRequired = false}) {
  return SizedBox(
    // width: 200,
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 16,
          color: isRequired ? Colors.red : Colors.grey[700],
        ),
      ),
    ),
  );
}

// 构建输入框装饰
InputDecoration _buildInputDecoration({
  required String hintText,
  required TextEditingController controller,
  Widget? suffixIcon,
}) {
  print('controller ${controller.text}');
  return InputDecoration(
    hintText: hintText,
    contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
    // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
    suffixIcon: suffixIcon,
    hintStyle: TextStyle(color: Colors.grey[500]),
    // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
    // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
    // 适用于需要节省空间或创建更紧凑布局的场景
    // isDense: true,
    filled: true,
    fillColor: Colors.grey[50],

    // suffixIcon: controller.text.isNotEmpty
    //             ? IconButton(
    //                 icon: Icon(Icons.clear, size: 20),
    //                 onPressed: () {
    //                   controller.clear();
    //                   // 需要通知父组件状态更新
    //                   if (mounted) {
    //                     setState(() {});
    //                   }
    //                 },
    //               )
    //             : null,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.blue, width: 2),
    ),
    errorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red),
    ),
    focusedErrorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red, width: 2),
    ),
  );
}

class StorageBatchItem {
  final String storageImSkuStorageBatchId;
  final String purchaseOrderNo;
  final String storagePutOnSaleNo;
  final String storageImSkuStorageSummaryId;

  StorageBatchItem({
    required this.storageImSkuStorageBatchId,
    required this.purchaseOrderNo,
    required this.storagePutOnSaleNo,
    required this.storageImSkuStorageSummaryId,
  });
  factory StorageBatchItem.fromJson(Map<String, dynamic> json) {
    return StorageBatchItem(
      storageImSkuStorageBatchId: json['storageImSkuStorageBatchId'],
      purchaseOrderNo: json['purchaseOrderNo'],
      storagePutOnSaleNo: json['storagePutOnSaleNo'],
      storageImSkuStorageSummaryId: json['storageImSkuStorageSummaryId'],
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'storageImSkuStorageBatchId': storageImSkuStorageBatchId,
      'purchaseOrderNo': purchaseOrderNo,
      'storagePutOnSaleNo': storagePutOnSaleNo,
      'storageImSkuStorageSummaryId': storageImSkuStorageSummaryId,
    };
  }
}
